# -*- coding: utf-8 -*-
# @Author  : JackRoc
# @FileName: cnbaowen.py
"""
俩张图片
一张有缺口 一张无缺口
通过对比俩张图片的像素点 找到缺口的位置

1.获取俩张图片
2.计算缺口的位置 得到x坐标
3.用selenium 模拟滑动轨迹 !!!
https://itpcb.com/a/1409213  pip install opencv-python  利用图像处理库cv2
"""
import time, re, requests, random
from io import BytesIO

from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By

from PIL import Image


def get_image(driver, name, class_name):
    # bg_images = driver.find_elements_by_class_name('gt_cut_bg_slice')
    bg_images = driver.find_elements_by_class_name(class_name)
    image_url = ''
    location_list = []
    for image in bg_images:
        # print(image.get_attribute('style'))
        location = {}
        image_url = re.findall(r'background-image: url\("(.*?)"\); background-position: (.*?)px (.*?)px;',
                               image.get_attribute('style'))[0][0]
        location['x'] = re.findall(r'background-image: url\("(.*?)"\); background-position: (.*?)px (.*?)px;',
                                   image.get_attribute('style'))[0][1]
        location['y'] = re.findall(r'background-image: url\("(.*?)"\); background-position: (.*?)px (.*?)px;',
                                   image.get_attribute('style'))[0][2]
        # print(image_url, location['x'], location['y'])
        location_list.append(location)
    print(image_url)
    response = requests.get(image_url).content
    image_content = BytesIO(response)
    # image = Image.open(image_content)
    # image.show()
    image = get_merge_image(image_content, location_list, name)
    image.save('{}.jpg'.format(name))
    return image
    # with open(name,'wb') as f:
    #     f.write(response)


def get_merge_image(image_content, location_list, name):
    image = Image.open(image_content)
    image_list_up = []
    image_list_down = []
    for location in location_list:
        if int(location['y']) == -58:
            image_list_up.append(image.crop((abs(int(location['x'])), 58, abs(int(location['x'])) + 10, 116)))
        if int(location['y']) == 0:
            image_list_down.append(image.crop((abs(int(location['x'])), 0, abs(int(location['x'])) + 10, 58)))

    new_image = Image.new('RGB', (260, 116))
    positon_x = 0
    for image in image_list_up:
        new_image.paste(image, (positon_x, 0))
        positon_x += 10
    positon_x = 0
    for image in image_list_down:
        new_image.paste(image, (positon_x, 58))
        positon_x += 10
    return new_image


def get_diff_location(image1, image2):
    for x in range(1, 259):
        for y in range(1, 115):
            # 判断成立 表示这俩个点 俩张图的像素点是不一样的
            if is_similar(image1, image2, x, y) == False:
                return x


def is_similar(image1, image2, x, y):
    pixel1 = image1.getpixel((x, y))  # 元祖
    pixel2 = image2.getpixel((x, y))

    for i in range(0, 3):
        if (abs(pixel1[i] - pixel2[i]) >= 50):
            return False
    return True


def get_track(x):
    """
    模拟 匀加速 再匀减速  加上来回滑动
    :return:
    """
    v = 0     # 初 速度
    t = 0.2   # 时间
    temp = 0  # 当前位置 初始值为0
    tracks = []
    mid = x * 5 / 8
    x = x + 10
    while temp < x:
        # a = 2
        if temp < mid:
            a = random.randint(1, 3)
        else:
            a = -random.randint(2, 4)
        v0 = v
        s = v0 * t + 0.5 * a * (t ** 2)
        temp += s
        tracks.append(round(s))
        v = v0 + a * t
    for i in range(4):
        tracks.append(-random.randint(2, 4))
    return tracks


def main(driver, elem):
    image1 = get_image(driver, 'bg', 'gt_cut_bg_slice')
    time.sleep(3)
    image2 = get_image(driver, 'full', 'gt_cut_fullbg_slice')
    # image_url = 'http://static.geetest.com/pictures/gt/c37cbee8b/c37cbee8b.webp'
    # with open('22.jpg', 'wb') as f:
    #     f.write(requests.get(image_url).content)
    x = get_diff_location(image1, image2)
    print(x)
    ActionChains(driver).click_and_hold(elem).perform()
    track = get_track(x)
    for x in track:
        ActionChains(driver).move_by_offset(xoffset=x, yoffset=0).perform()
    ActionChains(driver).release(elem).perform()
    time.sleep(2)


if __name__ == '__main__':
    url = 'http://www.cnbaowen.net/api/geetest/'

    driver = webdriver.Chrome()
    driver.maximize_window()

    driver.get(url)

    try:
        count = 5
        wait = WebDriverWait(driver, 15)

        elem = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'gt_slider_knob')))
        elem.click()
        while count > 0:
            main(driver, elem)
            try:
                # success = wait.until(EC.presence_of_element_located((By.XPATH,'//*[@id="captcha"]/div/div[3]/div[5]')))
                success = wait.until(
                    EC.presence_of_element_located((By.XPATH, '//div[@class="gt_slider"]/div[@class="gt_success"]')))
                if success:
                    print('success')
            except Exception as e:
                print(str(e))
                print('error')
                count -= 1
    finally:
        print('finsh')

    # 方式一
    # wait = WebDriverWait(driver, 15)
    #
    # elem = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'gt_slider_knob')))
    # image1 = get_image(driver, 'bg', 'gt_cut_bg_slice')
    # time.sleep(3)
    # image2 = get_image(driver, 'full', 'gt_cut_fullbg_slice')
    # x = get_diff_location(image1,image2)
    # print(x)
    # ActionChains(driver).click_and_hold(elem).perform()
    # x1 = x/2
    # # ActionChains(driver).move_by_offset(xoffset=x, yoffset=0).perform()
    # ActionChains(driver).move_by_offset(xoffset=x1, yoffset=0).perform()
    # time.sleep(2)
    # ActionChains(driver).move_by_offset(xoffset=x1, yoffset=0).perform()
    #
    # ActionChains(driver).release(elem).perform()
    # time.sleep(2)
